package com.example.servlet.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.model.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 用户登录
 */
@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json;charset=utf-8");
        BufferedReader reader = req.getReader();
        String str = null;
        while((str=reader.readLine())!=null){
            JSONObject jsonObject = JSON.parseObject(str);
            String username = jsonObject.getString("username");
            String password = jsonObject.getString("password");
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            ResponseData data = null;
            if(user != null){
                data = ResponseData.ok(user);
            }else{
                data = ResponseData.fail();
            }
            resp.getWriter().println(JSON.toJSONString(data));
        }
    }
}
